<?php


namespace App\Http\Controllers\Api;


use App\Constants\AdvConfigConstant;
use App\Constants\IntegralLogTypeConstant;
use App\Models\MemberIntegralLog;
use App\Models\MemberSignLog;
use App\Services\SignService;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class SignController extends Controller
{
    public function index(Request $request)
    {
        $memberId = auth('api')->user()->id;

        $ret = app(SignService::class)->sign($this->getMiniType(), $memberId);

        $signIntegral = MemberIntegralLog::query()->where('member_id', '=', $memberId)
            ->where('type', '=', IntegralLogTypeConstant::TYPE_BY_SIGN)
            ->where('mini_type', '=', $this->getMiniType())
            ->sum('change');

        $data = [
            'sum_sign_integral' => $signIntegral,
            'show_sign_video'   => $this->isShowSignVideo($memberId),
            'is_sign_date'      => $this->getSignDate($memberId),
        ];

        $data['sign'] = $ret;

        return $this->_success($data);
    }

    public function signDateLog(Request $request)
    {
        $date = $request->input('date');
        if (!$date) {
            return $this->error('日期不能为空');
        }

        $memberId = auth('api')->user()->id;

        return $this->_success([
            'date' => $this->getSignDate($memberId, $date)
        ]);
    }

    protected function getSignDate(int $memberId, ?string $date = null): array
    {
        if (is_null($date)) {
            $date = date('Y-m');
        }

        [$year, $month] = explode('-', $date);

        $ret = MemberSignLog::query()->where([
            'member_id' => $memberId,
            'year'      => $year,
            'month'     => $month,
            'mini_type' => $this->getMiniType(),
        ])->pluck('created_at')->all();

        foreach ($ret as &$item) {
            $item = date('Y-m-d', strtotime($item));
        }

        return $ret;
    }

    protected function isShowSignVideo(int $memberId): bool
    {
        $settings = getMiniSettings($this->getMiniType(), AdvConfigConstant::ADV_GROUP);
        $status = Arr::get($settings, AdvConfigConstant::SIGN_VIDEO_ADV_STATUS);

        if ($status == 1) {
            return !MemberIntegralLog::query()->where([
                'member_id' => $memberId,
                'type'      => IntegralLogTypeConstant::TYPE_BY_SIGN_VIDEO,
                'mini_type' => $this->getMiniType(),
            ])->whereDate('created_at', '=', date('Y-m-d'))->exists();
        }

        return false;
    }
}
